import { _decorator, Button, Color, Component, EventHandler, find, Graphics, Label, LabelOutline, Layers, Mask, Node, PolygonCollider2D, size, tween, UITransform, view, Widget } from 'cc';
import { CommonResourceManager } from './CommonResourceManager';
const { ccclass, property } = _decorator;

@ccclass('CommonManager')
export class CommonManager {
    public static instance: CommonManager | null;

    public static getInstance(): CommonManager {
        if (!CommonManager.instance) {
            CommonManager.instance = new CommonManager();
        }
        return CommonManager.instance;
    }

    public backCityCurrency(city, callback) {
        let json = CommonResourceManager.getInstance().backNationJson();
        if (json != null) {
            json.forEach((value) => {
                Object.keys(value).forEach(key => {
                    if (key == "国家码") {
                        if (city == value[key]) {
                            let rate = parseFloat(value["汇率"]);
                            let currency = value["货币"];
                            callback(rate, currency);
                        }
                    }
                });
            });
        }
    }

    public backCityLanguage(string) {
        let json = CommonResourceManager.getInstance().backNationFontJson();
        if (json != null) {
            return json[string]
        } else {
            return null;
        }
    }


    /**
    * 当前货币汇率
   */
    private _curCurrencyRate = 0;
    public backCurrencyRate() {
        return this._curCurrencyRate;
    }
    public setCurrencyRate(value) {
        this._curCurrencyRate = value;
        console.log(this._curCurrencyRate)
    }
    /**
     * 当前货币
    */
    private _curCurrency = "";
    public backCurrency() {
        return this._curCurrency;
    }
    public setCurrency(value) {
        this._curCurrency = value;
    }


    /**
     * 返货换算之后的货币字符串
     * @param value 
     * @param subBit  保留的小数点 
     * @param isMult  是否乘以倍数
     * @returns 
     */
    public backConverCurrencyString(value, subBit: number = -1, isMult: boolean = true) {
        if (typeof value === "string") {
            value = parseFloat(value);
        }
        if (isMult) {
            value = value * this._curCurrencyRate
        }
        if (subBit != -1) {
            value = value.toFixed(subBit)
        }
        return this._curCurrency + value;
    }

    /**
     * 当前字体语言信息
    */
    private _curLanguage = "";
    public setLanguage(value) {
        this._curLanguage = value;
    }

    /**
     * 返回对应国家的字体
    */
    public backFontLanguageString(name) {
        return this._curLanguage["name"];
    }


    //------------------------------

    /**
        * 添加button按钮
        * @param btn_cfg {node：给哪个节点添加按钮，target：脚本节点，component：组件名，handler：方法名}
        * @returns 
        */
    public addBtnEvent(btn_cfg: { node: Node, target: Node, component: string, handler: string, customEventData, transition: number }) {
        // node, target, component, handler
        if (!btn_cfg || !btn_cfg.node) return;
        let node = btn_cfg.node;
        if (!node.getComponent(Button)) {
            node.addComponent(Button);
        }
        let btn = node.getComponent(Button);
        let event = new EventHandler();
        event.target = btn_cfg.target;
        event.component = btn_cfg.component;
        event.handler = btn_cfg.handler;
        event.customEventData = btn_cfg.customEventData;
        btn.transition = btn_cfg.transition;
        btn.clickEvents[0] = event;
    }

    /**
     * 打乱数组顺序
     * @param arr 传入需要打乱的数组
     * @returns 
     */
    public _random_arr = function (arr) {
        /* if (arr instanceof Array) {  //该方法也能打乱数组但是打乱的不够彻底
            arr.sort(function () {
                return 0.5 - Math.random()
            })
            return arr
        } */

        if (!Array.isArray(arr)) return
        let new_arr = arr.concat()
        for (let i = 0; i < new_arr.length; i++) {
            let index = Math.floor(Math.random() * new_arr.length)
            let temp = new_arr[index]
            new_arr[index] = new_arr[i]
            new_arr[i] = temp
        }
        return new_arr
    }

    //根据平台修改风险提示
    /**
     * 
     * @param parentNode 父节点
     * @param platform 平台
     * @param isLandscape 是否横屏
     */
    public updateNotice(parentNode: Node, platform: string, isLandscape: boolean, callback: Function = null) {

        if (platform.toLowerCase() == "uac") {  //如果是UAC不需要风险提示
            return
        }
        let title = parentNode.getChildByName("title")

        if (!title) {
            title = new Node("title")
            title.setParent(parentNode)
            title.layer = Layers.Enum.UI_2D
            title.addComponent(UITransform)
            title.getComponent(UITransform).setContentSize(600, 50)
            let wg = title.addComponent(Widget)
            wg.isAlignLeft = true
            wg.left = 0
            wg.isAlignBottom = true
            wg.bottom = 0
            wg.target = find("Canvas")
            wg.alignMode = Widget.AlignMode.ALWAYS
            let lab = title.addComponent(Label)
            title.setSiblingIndex(100)

            lab.overflow = Label.Overflow.RESIZE_HEIGHT
            lab.isBold = true
            lab.horizontalAlign = Label.HorizontalAlign.LEFT
            lab.verticalAlign = Label.VerticalAlign.BOTTOM
            wg.updateAlignment()

            let labOut = title.addComponent(LabelOutline)
            labOut.color = new Color().fromHEX("#000000")
            labOut.width = 2
        }

        let lab = title.getComponent(Label)

        if (false) {    //遗弃Ads Only
            lab.fontSize = 35
            lab.lineHeight = 50
            lab.string = "Ads Only"

            title.getComponent(UITransform).setContentSize(size(view.getVisibleSize().width - 80, 50))
        } else if(platform.toLowerCase() == "tiktok"){
            lab.fontSize = 21
            lab.lineHeight = 21
            title.getComponent(UITransform).setContentSize(size(view.getVisibleSize().width - 80, 50))
            lab.string = "This is not a gambling game and does not have any means of winning any monetary rewards or prizes of monetary value in any manner whatsoever. Gambling is strictly prohibited."
        }
        else {
            lab.fontSize = 23
            lab.lineHeight = 23
            title.getComponent(UITransform).setContentSize(size(view.getVisibleSize().width - 80, 50))
            lab.string = "The final result is not guaranteed, and the amount you can get is subject to the rules published in the APP."
        }

        if (callback) callback(title)
        lab.updateRenderData(true)
    }

    /**
     * 获得机翻json对象的value  只适用于机翻插件一键生成的所有国家的json文件
     * @param json json脚本
     * @param country 国家
     * @param assignValue 指定返回的key，不传值就默认返回第一个key的值
     * @returns 
     */
    public getJsonBackValue(json: Object, country: string, assignValue: string = null) {
        for (const key in json) {
            const element = json[key];
            if (country.toUpperCase() === key.toUpperCase()) {
                for (const key1 in element) {
                    const value = element[key1];
                    //没有指定key就返回第一个属性值
                    if (!assignValue) return value

                    if (key1 == assignValue) {//返回指定的属性值
                        return value
                    }
                }
            }
        }
    }

    /**
  * 在固定时间内匀速从起始值到终止值
  * tweenFloat(0,100,10,(t)=>{
  *      console.log("每帧值==>",t)
  *  },()=>{
  *      console.log("完成")
  *  }
  * )
  * 
  * @param from 起始值
  * @param to 终止值
  * @param duration 时间
  * @param onUpdate 每帧时间 (t)=>{}
  * @param onComplete 结束方法
  * @param autoStart 是否直接开始执行
  * @returns 
  */
    public tweenFloat(from: number, to: number, duration: number, onUpdate: (t: number) => void, onComplete?: Function, autoStart: boolean = true) {
        let o: Record<string, number> = { _value: from };
        Object.defineProperty(o, 'value', {
            get: () => o._value,
            set: (v: number) => { o._value = v; onUpdate && onUpdate(o._value); },
        });
        let tween1 = tween(o).to(duration, { value: to }).call(onComplete);
        if (autoStart) {
            tween1.start();
        }
        return tween1;
    }

    /**
     * 自定义mask遮罩 需要延迟一帧使用
     * @param node 节点
     * @returns 
     */
    public poloyMask(node: Node) {
        if (!node.getComponent(Mask)) return console.error("节点不存在Mask组件")
        let grf: Graphics = node.getComponent(Mask)["_graphics"]
        if (!grf) return console.error("节点不存在_graphics,请延迟一帧使用")
        let cmp = node.getComponent(PolygonCollider2D)
        let offset = cmp.offset
        if (!cmp) return console.error("节点不存在 PolygonCollider2D组件")
        grf.moveTo(cmp.points[0].x + offset.x, cmp.points[0].y + offset.y)
        for (let i = 0; i < cmp.points.length; i++) {
            let point = cmp.points[i]
            grf.lineTo(point.x + offset.x, point.y + offset.y)
            if (i == cmp.points.length - 1) {
                grf.fill()
            }
        }
    }

    public findNodesByName(parent: Node, name: string, findNodes: Node[] = []) {
        if (parent == null) {
            findNodes = []
            parent = find("Canvas");
        }

        let list = parent.children;
        for (let index = 0; index < list.length; index++) {
            let node = list[index];
            if (node.name == name) {
                findNodes.push(node)
            } else {
                this.findNodesByName(node, name, findNodes);
            }
        }
        return findNodes;
    }
}

